package mq

import (
	"github.com/streadway/amqp"
	"log"
)

func  P2pSend(ch *amqp.Channel,queue string, body []byte) (err error) {
	var (
		q    amqp.Queue
	)
	defer ch.Close()

	if q, err = ch.QueueDeclare(
		queue, // name
		true,  // 用来定义队列是否要持久化，true=持久化队列，false=不持久化
		false, //是否在消费完成后自动删除队列，true=自动删除，false=不删除
		false, // exclusive //是否独占队列，true=独占队列，false=不独占队列
		false, // no-wait
		nil,   // arguments
	); err != nil {
		return
	}

	return ch.Publish(
		"",     // exchange
		q.Name, // routing key
		false,  // mandatory
		false,  // immediate
		amqp.Publishing{
			ContentType:  "text/plain",
			Body:         body,
			DeliveryMode: amqp.Persistent,
		})
}

func  P2pReceive(ch *amqp.Channel,queue string) (err error) {
	var (
		q    amqp.Queue

		msgs <-chan amqp.Delivery
	)

	if q, err = ch.QueueDeclare(
		queue, // name
		false, // durable
		false, // delete when unused
		false, // exclusive
		false, // no-wait
		nil,   // arguments
	); err != nil {
		return
	}

	if msgs, err = ch.Consume(
		q.Name, // queue
		"",     // consumer
		true,   // auto-ack
		false,  // exclusive
		false,  // no-local
		false,  // no-wait
		nil,    // args
	); err != nil {
		return
	}

	forever := make(chan bool)

	go func() {
		for d := range msgs {
			log.Printf("Received a message: %s", d.Body)
		}
	}()

	log.Printf(" [*] Waiting for messages. To exit press CTRL+C")

	<-forever
	return

}

